package team.seekers.catering.common.utils.message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import team.seekers.catering.common.enums.MessageEnum;


import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MessageUtils {

    private static String appId = "wxb92b270e362452bd";
    private static String secretId = "wxb92b270e362452bd";

    /**
     * 厨师完成订单，推送出餐信息
     */
    public static void sendCookingEndMessage(String userId, String showId,String foodName,String message){
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(userId);//用户的openid
        wxMssVo.setTemplate_id(MessageEnum.END_COOKING.getCode());//订阅消息模板id
        wxMssVo.setPage("pages/order/order");

        Map<String, TemplateData> m = new HashMap<>();
        m.put("character_string3", new TemplateData(showId));
        m.put("thing12", new TemplateData(foodName));
        m.put("thing1", new TemplateData(message));
        wxMssVo.setData(m);

        // 推送
        push(wxMssVo);
    }

    public static String getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", appId);
        params.put("APPSECRET", secretId);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String Access_Token = object.getString("access_token");
        String expires_in = object.getString("expires_in");
        System.out.println("有效时长expires_in：" + expires_in);
        return Access_Token;
    }

    public static void push(WxMssVo wxMssVo){
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token（实际开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class);
        log.info("返回的消息是 {} ",responseEntity.getBody());
    }

}
